using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cysharp.Threading.Tasks;
using System.Threading;

public class GameMgr : MonoBehaviour
{
    private GameObject m_BricksWallPfb;

    [SerializeField]
    private Transform m_BWSpownPoint, m_GameScene;

    private int m_BWallidx;
    private float m_SceneMoveSpeed;
    private float m_SpownCD;

    //private Timer m_SpownWallsTimer;
    private CancellationTokenSource m_Ctks;
    private void Awake()
    {
        Application.targetFrameRate = 60;

        m_BricksWallPfb = Resources.Load("Prefabs/BricksWall") as GameObject;

        StartGame();
    }

    private void StartGame()
    {
        //m_SpownWallsTimer = Timer.Register(1.2f, ShowBricksWall, isLooped: true);
        m_Ctks = new CancellationTokenSource();
        SpownLoop().Forget();
    }

    public async UniTask SpownLoop()
    {
        while (true)
        {
            ShowBricksWall();
            await UniTask.Delay(System.TimeSpan.FromSeconds(m_SpownCD), cancellationToken: m_Ctks.Token);
        }
    }

    public void ShowBricksWall()
    {
        m_BWallidx++;
        var bwctrl = Instantiate(m_BricksWallPfb, m_BWSpownPoint.position, Quaternion.identity, m_GameScene).GetComponent<BricksWallCtrl>();
        var data = new BricksData()
        {
            //MoveSpeed = 1.8f,
            RightIdx = GetUNReapitNum(),
        };
        bwctrl.SetState(data);

        if (m_BWallidx < 10)
        {
            m_SceneMoveSpeed = 1.2f;
            m_SpownCD = 1.4f;
        }
        else if (m_BWallidx < 20)
        {
            m_SceneMoveSpeed = 1.4f;
            m_SpownCD = 1.3f;

        }
        else if (m_BWallidx < 40)
        {
            m_SceneMoveSpeed = 1.6f;
            m_SpownCD = 1f;

        }
        else if (m_BWallidx < 50)
        {
            m_SceneMoveSpeed = 1.8f;
            m_SpownCD = 0.8f;

        }
        else
        {
            m_SceneMoveSpeed = 2f;
            m_SpownCD = 0.7f;

        }
    }

    List<int> nums = new List<int>() { 0, 1, 2, 3, 4 };
    int lastnum = -1;
    private int GetUNReapitNum()
    {

        int curnum = nums[Random.Range(0, nums.Count)];
        if (lastnum != -1)
            nums.TryAdd(lastnum);

        lastnum = curnum;
        nums.TryRemove(lastnum);
        return curnum;
    }

    private void FixedUpdate()
    {
        m_GameScene.Translate(Vector3.left * Time.deltaTime * m_SceneMoveSpeed);
    }
}
